package com.freedom.admin.application.service.cmd;

import com.freedom.admin.application.converter.RoleConverter;
import com.freedom.admin.domain.service.RoleMenuService;
import com.freedom.admin.domain.service.RolePermissionService;
import com.freedom.admin.domain.service.RoleService;
import com.freedom.admin.domain.service.UserRoleService;
import com.freedom.admin.infrastructure.persistence.pojo.bo.RoleBO;
import com.freedom.admin.infrastructure.persistence.pojo.form.RoleForm;
import com.freedom.admin.infrastructure.persistence.pojo.form.RoleResourceForm;
import com.freedom.admin.infrastructure.persistence.pojo.form.RoleStatusForm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RoleCmdService {

    private final RoleService roleService;

    private final UserRoleService userRoleService;

    private final RoleMenuService roleMenuService;

    private final RolePermissionService rolePermissionService;

    private final RoleConverter roleConverter;

    @Transactional(rollbackFor = Exception.class)
    public boolean addRole(RoleForm roleForm) {
        RoleBO roleBO = roleConverter.toBO(roleForm);
        roleService.add(roleBO);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean modifyRole(RoleForm roleForm) {
        RoleBO roleBO = roleConverter.toBO(roleForm);
        roleService.modifyRole(roleBO);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean removeRoles(List<Integer> roleIds) {
        roleService.removeRoles(roleIds);
        userRoleService.removeByRoleIds(roleIds);
        roleMenuService.removeByRoleIds(roleIds);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean modifyRoleStatus(RoleStatusForm roleStatusForm) {
        RoleBO roleBO = new RoleBO(roleStatusForm.getId(), roleStatusForm.getStatus());
        roleService.modifyRoleStatus(roleBO);
        return Boolean.TRUE;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean modifyRoleResource(RoleResourceForm roleResourceForm) {
        rolePermissionService.addRolePermission(roleResourceForm.getRoleId(), roleResourceForm.getPermIds());
        roleMenuService.addRoleMenu(roleResourceForm.getRoleId(), roleResourceForm.getMenuIds());
        return Boolean.TRUE;
    }
}
